/*
 * ptp2_master.c
 *
 *  Created on: 28 nov. 2013
 *      Author: crma
 */

#include "hcpp/ptp2_master.h"
#include "hcpp/ptp2_task_queue.h"
#include "hcpp/ptp2_log.h"
#include "hal/interval_timer_hal.h"
#include "hal/sysconf_hal.h"
#include "hal/tod_itf.h"

#include <stdio.h>

static void ptp2_master_destructor(void *ptr);

static class_info_t class_info = {
    .size        = sizeof(ptp2_master_t),
    .destructor  = ptp2_master_destructor,
    .mem_alloc   = NULL,
    .mem_free    = NULL
};

static ptp2_master_t master;

bool
ptp2_master_init(void)
{
    /* init object */
    object_init(&master, &class_info);

    /* set running flag */
    master.running = true;


    /* print version */
    PTP2_LOG_PRINTLN(PTP2_LOG_MASTER, PTP2_LOG_INFO, ("Hardware SVN Revision %ld (svn info in ./trunk/hdl)", sysconf_hal_get_hw_rev_number() ));
    PTP2_LOG_PRINTLN(PTP2_LOG_MASTER, PTP2_LOG_INFO, ("Software SVN Revision %s (svnversion)", sysconf_hal_get_sw_rev_number() ));

#ifdef __NIOS2__
    av_bus_write_32(HOST_REG_USER0, 0);
#endif

    if (!ptp2_task_queue_init(PTP2_TASK_QUEUE())) {
        return false;
    }

    /* 2. depends on task queue initialization */
    if (!interval_timer_hal_init()) {
        return false;
    }

    if(!spi_master_init(&master.spi_master)){
        return false;
    }
/**/ //not yet
    if (tod_itf_open(&(master.tod)) == -1) {
        PTP2_LOG_PRINTLN(PTP2_LOG_MASTER, PTP2_LOG_ERROR, ("uart_tod could not be open" ));
        return false;
    }
/**/

    return true;
}

static void
ptp2_master_destructor(void *ptr)
{
    //ptp2_master_t *master = ptr;

}



bool
ptp2_master_mainloop(void)
{
    ptp2_task_t    *task;
    int retval;
    int mm;

    fprintf(stderr, "\n>>");

    while (master.running) {
      if ((task = ptp2_task_queue_next(PTP2_TASK_QUEUE())) != NULL) {

          ptp2_log_bit_set(3);

          task->execute(task->ref, task->param);
          object_release(task);

          ptp2_log_bit_clear(3);


          /*retval = fscanf(stderr, "%d", &mm);
          if(retval > 0){
            fprintf(stderr, "Ricevuto %d valore, mm:%d\n", retval, mm);
            fprintf(stderr, "\n>>");
          }*/
      }
    }

    return true;
}
